import React, { Component, PropTypes } from 'react';
import { Router, Route, IndexRoute, browserHistory, Link } from 'react-router';
import { connect } from 'react-redux';
import { Tool, merged } from '../Tool';
import Util from '../utils/Util';
import { Card, Form, Input, Tooltip, Icon, Cascader, Select, Row, Col, Checkbox, Button,Modal,Spin,Table,InputNumber,message} from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
import {openExpertFormModel,ExpertInfoModel,LoadExpertLab,LoadExpertOrg,LoadExpertUpdate,showCommonLoading,loadCommonList,showCommonlistLoading} from '../action/Action';

/**
 * 专家列表
 * @export
 * @class ExpertList
 * @extends {Component}
 */
class ExpertListLi extends Component {
    constructor(props){
        super(props);
        this.columns = [{
            title: '专家名',
            dataIndex: 'name',
            width:'10%'
        }, {
            title: '机构',
            width:'30%',
            render:(text, record)=>(
                record.org+(Util.IsNull(record.college)?"":("/"+record.college))+(Util.IsNull(record.dept)?"":("/"+record.dept))
            )
        },{
            title: '实验室',
            dataIndex: 'lab',
            width:'30%'
        },{
            title: '职位',
            dataIndex: 'title',
            width:'10%'
        }, {
            title: '手机',
            dataIndex: 'mobile',
            width:'10%'
        }, {
            title: '操作',
            dataIndex: 'address',
            width:'10%',
            render: (text, record) =>(
                <Button type="primary" onClick={() =>this.openModel(record.uid)}>编辑</Button>
            )
        }];
        this.state= {
            loading: true,
            pagination: {
                defaultCurrent:1,
                total:0,pageSize:10
            },
        }
        let {Expert,dispatch} = this.props;
        this.handleTableChange=(pagination, filters, sorter)=>{
            var pages = pagination.current-1;
            dispatch(showCommonlistLoading(true));
            dispatch(loadCommonList("set_expert_list","ExpertList",pages,10));//初始加载
        }
        this.openModel=(uid)=>{
            let{dispatch} = this.props;
            dispatch(ExpertInfoModel(uid));
            dispatch(openExpertFormModel(true));
        }
    }
    render() {
        let {Expert,paginationFlag,CommonSystem} = this.props;
        const pagination = {...this.state.pagination};
        var lis = Expert.list;
        if(lis && lis.content && lis.content.length>0){
            pagination.total = lis.totalElements;
            pagination.pageSize = lis.size;
            pagination.defaultCurrent = lis.number+1;
        }
        return (
            <Row gutter={16}>
                <Col className="gutter-row" span={24}>
                    <div className="gutter-box">
                        <Card title="专家列表" bordered={false}>
                            <Table columns={this.columns} rowKey="uid" dataSource={Expert.list.content} loading={CommonSystem.listLoading} pagination={paginationFlag?pagination:false} onChange={this.handleTableChange}/>
                        </Card>
                    </div>
                </Col>
            </Row>
        );
    }
}
var ExpertList = connect(state=>({
    User: state.User,
    Expert:state.Expert,
    CommonSystem:state.CommonSystem
}))(ExpertListLi);
/**
 * 编辑和新增专家
 * @export
 * @class ExpertInfo
 * @extends {Component}
 */

const residences = [{
    value: 'zhejiang',
    label: 'Zhejiang',
    /*children: [{
     value: 'hangzhou',
     label: 'Hangzhou',
     children: [{
     value: 'xihu',
     label: 'West Lake',
     }],
     }],*/
}, {
    value: 'jiangsu',
    label: 'Jiangsu',
    /*children: [{
     value: 'nanjing',
     label: 'Nanjing',
     }],*/
}];
/*
 *
 public String name;专家名
 @Email
 public String email;邮箱
 public String org;一级机构，清华大学
 public String dept;三级机构
 public String lab;实验室
 public String title;职位
 public String resume;简历
 public String honors;头衔
 public int hindex;h因子
 public int domain;领域
 public String mobile;手机号
 public String phone;办公室电话
 *
 *
 * */
var form_uid = "";
class ExpertFormLi extends Component {
    componentDidMount(){

    }
    constructor(props){
        super(props);
        /* 获取数据类型 */
        let {Expert,dispatch} = this.props;
        this.state = {
            visible: Expert.form.visible,
            orgs:[],loading:false
        };

        this.onCancel=()=>{
            /* 关闭 */
            dispatch(openExpertFormModel(false))
        }
        this.onCreate=(e)=>{
            /* 增加 */
            this.handleSubmit(e);
        }
        this.handleSubmit = (e) => {
            e.preventDefault();
            this.props.form.validateFieldsAndScroll((err, values) => {
                if (!err) {
                    let {dispatch} = this.props;
                    var newValue = values;
                    newValue.lab = values.lab&&values.lab.length>0?values.lab[0]:"";
                    newValue.org = values.orgList[0];
                    newValue.college = values.orgList.length>0?values.orgList[1]:"";
                    newValue.dept = values.orgList.length>1?values.orgList[2]:"";
                    if(!Util.IsNull(values.domain)){
                        newValue.domain = Util.getFieldByName(values.domain);
                    }else{
                        newValue.domain = Expert["info"].expert.domain
                    }
                    var honArr = "";
                    console.log(values.honors)
                    if(values.honors && values.honors.length>0){
                        values.honors.map(function(ite){
                            honArr +=(honArr.length>0?",":"")+Util.getHonorsByName(ite);
                        })
                        console.log(honArr);
                    }else{
                        honArr = Expert["info"].honors;
                    }
                    newValue.honors = honArr;
                    dispatch(showCommonLoading(true));
                    if(!Util.IsNullJson(Expert["info"].expert)){
                        newValue.uid = Expert["info"].expert.uid;
                        dispatch(LoadExpertUpdate("PUT",newValue))
                    }else{
                        dispatch(LoadExpertUpdate("POST",newValue))
                    }
                }else{
                    console.log(err);
                }
            });
        };
    }
    componentWillMount(){
        let {dispatch} = this.props;
        dispatch(LoadExpertLab("清华大学"));
        dispatch(LoadExpertOrg("清华大学"));
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        let {Expert,CommonSystem,form} = this.props;
        var expertInfo = Expert["info"].expert;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span:6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
        };
        const tailFormItemLayout = {
            wrapperCol: {
                xs: {
                    span: 24,
                    offset: 0,
                },
                sm: {
                    span: 14,
                    offset: 8,
                },
            },
        };
        const prefixSelector = getFieldDecorator('prefix', {
            initialValue: '86',
        })(
            <Select className="icp-selector" style={{width: '60px'}}>
                <Option value="86">+86</Option>
            </Select>
        );
        const children = [],childrenHon=[];
        Util.getField().map(function (item) {
            children.push(<Option value={item.title+""} key={item.id}>{item.title}</Option>);
        });
        Util.getHonors().map(function(item){
            childrenHon.push(<Option value={item.title+""} key={item.id+""}>{item.title}</Option>);
        });
        const labs = [];
        if(Expert["info"].lab && Expert["info"].lab.length>0){
            Expert["info"].lab.map(function(labItem){
                var arr = {
                    value: labItem,
                    label: labItem
                }
                labs.push(arr);
            })
        }

        var orgs = [];
        const inOrgs = Expert["info"].org;
        if(inOrgs && inOrgs.length>0){
            function arrInit(arrList){
                if(arrList && arrList.length>0){
                    var orgArr = [];
                    arrList.map(function (ite) {
                        var arrss = {};
                        arrss.label=ite.org;
                        arrss.value=ite.org;
                        if(ite.colleges && ite.colleges.length>0){
                            var tColl = ite.colleges,tArr=[];
                            tColl.map(function(j){
                                tArr.label=j.org;
                                tArr.value=j.org;
                            })
                            arrss.children=arrInit(ite.colleges);
                        }
                        orgArr.push(arrss)
                    })
                    return orgArr;
                }else{
                    return null;
                }
            }
            orgs = arrInit(inOrgs);
        }

        return (
            <Modal
                visible={Expert['form'].visible}
                title="新增专家"
                okText="提交"
                onCancel={this.onCancel}
                onOk={this.onCreate}
                width={700}
            >
                <Spin spinning={CommonSystem.loading} delay={500} tip="正在提交">
                    <Form onSubmit={this.handleSubmit}>
                        <FormItem
                            {...formItemLayout}
                            label={(
                                <span>
                                姓名&nbsp;
                                    <Tooltip title="专家的真实姓名">
                                <Icon type="question-circle-o" />
                              </Tooltip>
                            </span>
                            )}
                            hasFeedback
                        >
                            {getFieldDecorator('name', {
                                rules: [{ required: true, message: '请输入姓名', whitespace: true }],
                            })(
                                <Input />
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="邮箱"
                            hasFeedback
                        >
                            {getFieldDecorator('email', {
                                rules: [{type:"email",message:"邮箱格式不正确"},{ required: true, message: '请输入电子邮箱', whitespace: true }],
                            })(
                                <Input />
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="机构"
                        >
                            {getFieldDecorator('orgList', {
                                initialValue: [],
                                rules: [{ type: 'array', required: true, message: '请选择专家的院系' }],
                            })(
                                <Cascader options={orgs} placeholder="请选择机构"/>
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="实验室"
                        >
                            {getFieldDecorator('lab', {
                                rules: [{ required: false, message: '请选择专家的实验室',type: 'array' }],
                            })(
                                <Cascader options={labs} />
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="职位"
                            hasFeedback
                        >
                            {getFieldDecorator('title', {
                                rules: [{ required: true, message: '请输入职位', whitespace: true }],
                            })(
                                <Input />
                            )}
                        </FormItem>

                        <FormItem
                            {...formItemLayout}
                            label="简历"
                            hasFeedback
                        >
                            {getFieldDecorator('resume', {
                                rules: [{ required: true, message: '请输入简历', whitespace: true }],
                            })(
                                <Input type="textarea" rows={4}/>
                            )}
                        </FormItem>

                        <FormItem
                            {...formItemLayout}
                            label="头衔"
                            hasFeedback
                        >
                            {getFieldDecorator('honors', {
                                rules: [{ required: false, message: '请输入头衔'}],
                            })(
                                <Select
                                    multiple
                                    style={{ width: '100%' }}
                                    placeholder="请选择头衔"
                                >
                                    {childrenHon}
                                </Select>
                            )}
                        </FormItem>

                        <FormItem
                            {...formItemLayout}
                            label="h因子"
                            hasFeedback
                        >
                            {getFieldDecorator('hindex',  { initialValue: 0 })(
                                <InputNumber min={0}/>
                            )}
                        </FormItem>

                        <FormItem
                            {...formItemLayout}
                            label="领域"
                            hasFeedback
                        >
                            {getFieldDecorator('domain', {
                                rules: [{ required: true, message: '请选择领域'}],
                            })(
                                <Select
                                    style={{ width: '100%' }}
                                    placeholder="选择领域"
                                >
                                    {children}
                                </Select>
                            )}
                        </FormItem>

                        <FormItem
                            {...formItemLayout}
                            label="手机号"
                        >
                            {getFieldDecorator('mobile', {
                                rules: [{ required: true, message: '请输入你的电话号码!' }],
                            })(
                                <Input addonBefore={prefixSelector} />
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="办公室电话"
                        >
                            {getFieldDecorator('phone', {
                                rules: [{ required: true, message: '请输入您的办公室电话号码!' }],
                            })(
                                <Input />
                            )}
                        </FormItem>
                        {/*<FormItem {...tailFormItemLayout}>
                         <Button type="primary" htmlType="submit" size="large">确认</Button>
                         </FormItem>*/}
                    </Form>
                </Spin>
            </Modal>
        );
    }
}

var ExpertForm = connect(state=>({
    User: state.User,
    Expert:state.Expert,
    CommonSystem:state.CommonSystem
}))(Form.create({
    mapPropsToFields(props){
        let {Expert} = props;
        var expertInfo = Expert["info"].expert;
        if(expertInfo && !Util.IsNullJson(expertInfo)){
            form_uid = expertInfo.uid;
            var labsAr = [],orgList = [],honorsList=[];
            orgList.push(expertInfo.org);
            if(expertInfo.college){orgList.push(expertInfo.college);}
            if(expertInfo.dept){orgList.push(expertInfo.dept);}
            console.log(orgList);
            labsAr.push(expertInfo.lab)
            if(!Util.IsNull(expertInfo.honors)){
                expertInfo.honors.trim().split(",").map(function(i){
                    honorsList.push(Util.getHonorsById(i));
                })
                console.log(honorsList)
            }
            console.log(expertInfo)
            console.log(Util.getFieldById(expertInfo.domain))
            return ({
                name:{
                    ...props.name,
                    value:expertInfo.name
                },
                email:{
                    ...props.email,
                    value:expertInfo.email
                },
                resume:{
                    ...props.resume,
                    value:expertInfo.resume
                },
                honors:{
                    ...props.honors,
                    value:honorsList
                },
                hindex:{
                    ...props.hindex,
                    value:expertInfo.hindex
                },
                domain:{
                    ...props.domain,
                    value:Util.getFieldById(expertInfo.domain)
                },
                mobile:{
                    ...props.mobile,
                    value:expertInfo.mobile
                },
                phone:{
                    ...props.phone,
                    value:expertInfo.office_phone
                },
                lab:{
                    ...props.lab,
                    value:labsAr
                },
                orgList:{
                    ...props.orgList,
                    value:orgList
                },
                title:{
                    ...props.title,
                    value:expertInfo.title
                }
            })
        }else {
            return {}
        }
    }
})(ExpertFormLi));

export {ExpertForm,ExpertList}



